import axios from 'axios'
import { Message } from 'element-ui'
import { getTokenStorage, getUsernameStorage } from './app'

class Http {
  constructor (options) {
    this.baseURL = options.baseURL ? options.baseURL : '/api'
    this.timeout = options.timeout ? options.timeout : 5000
    this.headers = options.headers ? options.headers : {}
    this.myAxios = null
    this.createAxios()
    this.configInterceptos()
  }

  createAxios () {
    if (this.myAxios) return
    this.myAxios = axios.create({
      baseURL: this.baseURL,
      timeout: this.timeout,
      headers: this.headers
    })
  }

  configInterceptos () {
    this.myAxios.interceptors.request.use(config => {
      config.headers.Tokey = getTokenStorage()
      config.headers.UserName = getUsernameStorage()
      return config
    }, (err) => {
      return Promise.reject(err)
    })

    this.myAxios.interceptors.response.use(res => {
      if (res.data.resCode !== 0) {
        Message({
          type: 'warning',
          message: res.data.message
        })
      }
      return res
    }, (err) => {
      return Promise.reject(err)
    })
  }

  getConfig () {
    const baseConfig = {
      method: 'get'
    }
    return baseConfig
  }

  request (config) {
    const baseConfig = this.getConfig()
    Object.assign(baseConfig, config)
    return this.myAxios(baseConfig)
  }
}

const baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_API : process.env.VUE_APP_API
const myAxios = new Http({
  baseURL: baseURL,
  timeout: 5000
})

export default myAxios
